import { Entity, PrimaryGeneratedColumn, Column, ILike, ManyToOne, JoinColumn } from 'typeorm';
import { AppDataSource } from '../config/db.js';
import { User } from './user.entity.js'; // 假设 User 实体在 user.entity.ts 文件中

@Entity('todos') // 指定数据库表名为 'todos'
export class Todo {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column({ nullable: true })
  description: string;

  @Column({ default: false })
  completed: boolean;

  // 新增所属用户多对一的关联字段
  @ManyToOne(() => User, user => user.todos)
  // @JoinColumn({ name: 'user_id' })
  user: User;

  // 创建增删改查函数

  /**
   * 创建一个新的Todo项
   * @param todo 包含title、description、completed和user的Todo对象
   * @returns 创建成功的Todo项
   */
  static async createTodo(todo: { title: string; description?: string; completed?: boolean; user: User }) {
    const todoRepository = AppDataSource.getRepository(Todo);
    const newTodo = todoRepository.create(todo);
    return await todoRepository.save(newTodo);
  }

 /**
   * 更新一个Todo项
   * @param id Todo项的ID
   * @param todo 包含要更新的字段的Todo对象
   * @returns 更新后的Todo项
   */
 static async updateTodo(id: number, todo: { title: string; description: string; completed: boolean }) {
  const todoRepository = AppDataSource.getRepository(Todo);
  await todoRepository.update({ id }, todo);
  return await todoRepository.findOneBy({ id });
}
  /**
   * 根据ID获取一个Todo项
   * @param id Todo项的ID
   * @returns 找到的Todo项，如果未找到则返回undefined
   */
  static async getTodoById(id: number) {
    const todoRepository = AppDataSource.getRepository(Todo);
    return await todoRepository.findOne( {
      where: {
      id,
      },
      relations: {
        user: true,
      }
});
  }

  /**
   * 根据页码、每页数量、标题关键字和完成状态获取Todo项列表
   * @param page 页码，从1开始，默认值为1
   * @param limit 每页数量，默认值为10
   * @param title 标题关键字，用于筛选标题包含该关键字的Todo项
   * @param completed 完成状态，用于筛选已完成或未完成的Todo项
   * @returns 包含当前页数据、总记录数、当前页码、每页大小和总页数的对象
   */
  static async getAllTodos(page: number = 1, limit: number = 10, title?: string, completed?: boolean) {
    const todoRepository = AppDataSource.getRepository(Todo);
    const skip = (page - 1) * limit;
    const whereClause: any = {};

    if (title) {
      whereClause.title =  ILike(`%${title}%`);
    }

    if (completed !== undefined) {
      whereClause.completed = completed;
    }

    const [items, total] = await todoRepository.findAndCount({
      where: whereClause,
      skip,
      take: limit
    });

    const pages = Math.ceil(total / limit);
    return {
      items,
      total,
      page,
      pageSize: limit,
      pages
    };
  }

  /**
   * 根据ID删除一个Todo项
   * @param id Todo项的ID
   * @returns 删除操作的结果
   */
  static async deleteTodo(id: number) {
    const todoRepository = AppDataSource.getRepository(Todo);
    return await todoRepository.delete({ id });
  }
/**
   * 根据用户id、页码、每页数量、标题关键字和完成状态进行分页查询
   * @param user_id 用户id
   * @param page 页码，从1开始，默认值为1
   * @param limit 每页数量，默认值为10
   * @param title 标题关键字，用于筛选标题包含该关键字的Todo项
   * @param completed 完成状态，用于筛选已完成或未完成的Todo项
   * @returns 包含当前页数据、总记录数、当前页码、每页大小和总页数的对象
   */
static async paginateTodos2(user_id:number=0,page: number = 1, limit: number = 10, title?: string, completed?: boolean|undefined) {
  const todoRepository = AppDataSource.getRepository(Todo);
  const skip = (page - 1) * limit;
  const whereClause: any = {};
  if (user_id) {
    whereClause.user = { id: user_id };
  }
  if (title) {
    whereClause.title = ILike(`%${title}%`);
  }

  if (completed !== undefined) {
    whereClause.completed = completed;
  }

  const [items, total] = await todoRepository.findAndCount({
    where: whereClause,
    skip,
    take: limit,
    order: {
      id: 'DESC' // 按 id 逆序排序
    }
  });

  const pages = Math.ceil(total / limit);
  return {
    items,
    total,
    page,
    pageSize: limit,
    pages
  };
}
  /**
   * 根据页码、每页数量、标题关键字和完成状态进行分页查询
   * @param page 页码，从1开始，默认值为1
   * @param limit 每页数量，默认值为10
   * @param title 标题关键字，用于筛选标题包含该关键字的Todo项
   * @param completed 完成状态，用于筛选已完成或未完成的Todo项
   * @returns 包含当前页数据、总记录数、当前页码、每页大小和总页数的对象
   */
  static async paginateTodos(page: number = 1, limit: number = 10, title?: string, completed?: boolean|undefined) {
    const todoRepository = AppDataSource.getRepository(Todo);
    const skip = (page - 1) * limit;
    const whereClause: any = {};

    if (title) {
      whereClause.title = ILike(`%${title}%`);
    }

    if (completed !== undefined) {
      whereClause.completed = completed;
    }

    const [items, total] = await todoRepository.findAndCount({
      where: whereClause,
      skip,
      take: limit,
      order: {
        id: 'DESC' // 按 id 逆序排序
      }
    });

    const pages = Math.ceil(total / limit);
    return {
      items,
      total,
      page,
      pageSize: limit,
      pages
    };
  }
}
